package com.ithzl.capacity.controller;

import com.ithzl.capacity.pojo.RESTful.RestBean;
import com.ithzl.capacity.pojo.User;
import com.ithzl.capacity.pojo.dto.UserPageDTO;
import com.ithzl.capacity.service.UserService;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();

    /**
     * 修改密码
     * @param session
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @PostMapping("/changePassword")
    public RestBean changePassword(HttpSession session,
                                   @Param("oldPassword") String oldPassword,
                                   @Param("newPassword") String newPassword){
        // 获取登录的用户
        User user= (User) session.getAttribute("user");

        boolean b=false;
        if (user!=null){
            // 检查旧密码是否相同
            if (bCryptPasswordEncoder.matches(oldPassword,user.getPassword())){
                // 加密
                String password=bCryptPasswordEncoder.encode(newPassword);

                // 调用修改
                b = userService.changePassword(user, password);
            }
            else {
                return RestBean.fail("旧密码输入错误");
            }
        }
        else {
            return RestBean.fail("用户登录过期");
        }

        // 返回
        return b?RestBean.succeed("修改成功"):RestBean.fail("修改失败，请联系管理员");
    }

    /**
     * 查询账号列表
     * @param userPageDTO
     * @return
     */
    @PostMapping("/inquireUserList")
    public RestBean inquireUserList(UserPageDTO userPageDTO){
        List<User> userList=userService.inquireUserList(userPageDTO);
        return RestBean.succeed(userList);
    }

    /**
     * 新增账号
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    public RestBean addUser(User user){
        userService.addUser(user);
        return RestBean.succeed(user);
    }

    /**
     * 账号修改(不修改密码)
     * @param user
     * @return
     */
    @PostMapping("/amendUser")
    public RestBean amendUser(User user){
        userService.amendUser(user);
        return RestBean.succeed(user);
    }

    @GetMapping("/delete")
    public RestBean deleteUser(@PathParam("id") int id){
        userService.deleteUser(id);
        return RestBean.succeed();
    }

}
